#include "encode_decode.h"
#include <string.h>

Lora_Data_Pack * Create_Recv_Lora_Data_Pack(uint8_t *pdata, int16_t len)
{
    Lora_Data_Pack *pp = (Lora_Data_Pack *)malloc(sizeof(Lora_Data_Pack));
    // Lora_Data_Pack dp = {};
    memcpy(&(pp->Head), pdata, 2);
    pp->Length = pdata[2];
    memcpy(&(pp->WanAddr), pdata + 3, 2);
    memcpy(&(pp->LanAddr), pdata + 5, 2);
    pp->ProtocolVersion = pdata[7];
    pp->Payload = (uint8_t *)malloc(len - 11);
    memcpy(pp->Payload, pdata + 8, len - 11);
    pp->CheckSum = pdata[len - 3];
    memcpy(&(pp->End), pdata + len - 2, 2);
    return pp;
}

Validate_Status isPackageValid(uint8_t *pdata, int16_t len)
{
    uint8_t cs = CheckSum(pdata, len - 3);
    if (cs == pdata[len - 3] && pdata[2] == len)
    {
        return VS_OK;
    }
    return VS_FAIL;
}

uint8_t CheckSum(uint8_t *pdata, int16_t len)
{
    int16_t i = 0;
    uint8_t res = 0;
    for (i = 0; i < len; i++)
    {
        res += pdata[i];
    }
    return res;
}
